package servlet;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.*;
import java.util.Scanner;

public class LoginServlet {
    public static void main(String[] args) throws SQLException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名");
        String name = sc.nextLine();
        System.out.println("请输入密码");
        String password = sc.nextLine();
        login(name,password);
//        login1(name,password);
    }
    //sql注入   用Statement 作为可执行对象
    public static void login(String username,String password) throws SQLException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        Connection con = dataSource.getConnection();
        Statement st = con.createStatement();
        //账户 username  和密码password
        //1.账户和密码都不知道    用户名：asfd  'or' 1=1 '#;    密码：13144654as
        //2.知道账户不知到密码    用户名：admin ';#      密码：1235466aa
        String sql = "select * from user where username ='" + username + "'and password='"+password+"'";
        ResultSet rs = st.executeQuery(sql);
        if (rs.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
        rs.close();
        st.close();
        con.close();
    }
    /*
   sql注入解决
    */
    public static void login1(String username,String password) throws SQLException {
        ComboPooledDataSource  dataSource = new ComboPooledDataSource();
        Connection con = dataSource.getConnection();
        String sql = "select * from user username = ? and password = ?";
        PreparedStatement ps  = con.prepareStatement(sql);
        //给?占位符赋值
        ps.setString(1,username);
        ps.setString(2,password);
        ResultSet rs  = ps.executeQuery();
        if (rs.next()){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }
        rs.close();
        ps.close();
        con.close();

    }
}
